package ClientNet;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.HashMap;

import Client.Client;
import ClientController.ListenerForServer;
import Protocol.user.BasePersonInfo;

public class ClientNet implements NetService {
	private Socket			    clientSocket;
	private ObjectOutputStream	out;
	private ObjectInputStream	in;
	private Client			    client;
	private HashMap<BasePersonInfo, ObjectOutputStream>    targetOutMap;
	
	public ClientNet(Client c) {
		client = c;
		targetOutMap = new HashMap<BasePersonInfo, ObjectOutputStream>();
	}
	private void establishListener(BasePersonInfo  target) {
		if(target.getUser_id() == -1) { //  target is server
			Thread		newThread = new Thread(new ListenerForServer(client, in));
			newThread.start();
		}
	}
	public boolean connectTo(BasePersonInfo target) {
		// TODO Auto-generated method stub
		boolean result = false ;
		try {
		    clientSocket = new Socket(target.getNetAddress().getIp(), target.getNetAddress().getPort());
			out = new ObjectOutputStream(clientSocket.getOutputStream());
			in = new ObjectInputStream(clientSocket.getInputStream()); 
			client.setOnline(true);
			targetOutMap.put(target, out);
			establishListener(target);
			result = true;
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			//displayServerFailure();
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			//displayServerFailure();
			e.printStackTrace();
		}
		return result;
	}

	@Override
	public boolean disconnectTo(BasePersonInfo target) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean establishListener(BasePersonInfo targetBasic,
			Runnable listener) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean sendMsgTo(BasePersonInfo target, Object msg) {
		// TODO Auto-generated method stub
		try {
			targetOutMap.get(target).writeObject(msg);
			targetOutMap.get(target).flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return false;
	}

}
